<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <!-- 表单部分 -->
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-row>
        <!-- 项目编号 -->
        <el-col :span="12">
          <el-form-item label="项目编号" prop="projectCode">
            <el-select v-model="dataForm.projectCode" placeholder="请选择项目编号" class="label_len"
                       :disabled="selectDis">
              <el-option v-for="item in projectList" :key="item.prProjectNumber"
                         :label="item.prProjectNumber + item.prProjectName" :value="item.prProjectNumber">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 表格部分 -->
      <el-table v-model="tableData" :data="tableData" style="width: 100%">
        <el-table-column prop="points" label="测点"></el-table-column>
        <el-table-column prop="samplingDepth" label="取样深度 cm"></el-table-column>

        <!-- 土壤含水率列，包含湿重、干重、土壤含水率百分比的输入框 -->
        <el-table-column label="土壤含水率">
          <el-table-column label="湿重g">
            <template slot-scope="scope">
              <el-input v-model="scope.row.wetWeight" placeholder="请输入湿重" size="small"
                        @input="calculateSoilMoisture(scope.row)" type="number"
                        :rules="[{ required: true, message: '湿重不能为空', trigger: 'blur' }]"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="干重g">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dryWeight" placeholder="请输入干重" size="small"
                        @input="calculateSoilMoisture(scope.row)" type="number"
                        :rules="[{ required: true, message: '干重不能为空', trigger: 'blur' }]"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="土壤含水率%">
            <template slot-scope="scope">
              <el-input v-model="scope.row.soilMoisture" placeholder="土壤含水率" size="small" disabled></el-input>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 土壤坚实度列 -->
        <el-table-column prop="soilSolidity" label="土壤坚实度(kPa)">
          <template slot-scope="scope">
            <el-input v-model="scope.row.soilSolidity" placeholder="请输入土壤坚实度" size="small" type="number"
                      :rules="[{ required: true, message: '土壤坚实度不能为空', trigger: 'blur' }]"
                      @input="calculateSoilMoisture(scope.row)"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <p>0~10层平均值：</p>
      <el-row style="margin-top: 20px">
        <el-col :span="12">
          <el-form-item label="土壤含水率">
            <el-input v-model="dataForm.waterLayerAverages10" :disabled="true" placeholder="" type="number"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="土壤坚实度">
            <el-input v-model="dataForm.soilLayerAverages10" placeholder="" disabled type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <p style="">10~20层平均值：</p>
      <el-row style="margin-top: 20px">
        <el-col :span="12">
          <el-form-item label="土壤含水率">
            <el-input v-model="dataForm.waterLayerAverages20" :disabled="true" placeholder="" type="number"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="土壤坚实度">
            <el-input v-model="dataForm.soilLayerAverages20" placeholder="" disabled type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <p style="color: red">总平均值：</p>
      <el-row style="margin-top: 20px">
        <el-col :span="12">
          <el-form-item label="土壤含水率计算值">
            <el-input v-model="dataForm.computeWaterAvg" :disabled="true" placeholder="" type="number"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="土壤含水率校验值">
            <el-input v-model="dataForm.waterAvg" placeholder="" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-col :span="12">
          <el-form-item label="土壤坚实度计算值">
            <el-input v-model="dataForm.computeSoilAvg" :disabled="true" placeholder="" type="number"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="土壤坚实度校验值">
            <el-input v-model="dataForm.soilAvg" placeholder="" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        projectCode: '',
        waterLayerAverages10: '',
        waterLayerAverages20: '',
        soilLayerAverages10: '',
        soilLayerAverages20: '',
        waterAvg: '',
        soilAvg: '',
        detectPeople: '',
        recorders: '',
        checkers: '',
        pdfPath: '',
        wordPath: '',
        status: '',
        soliChilds: this.tableData,
        computeWaterAvg:'',
        computeSoilAvg:'',
      },
      selectDis: false,
      projectList: [],
      tableData: [
        {points: 1, samplingDepth: "0~10", type: 1, wetWeight: "", dryWeight: "", soilMoisture: "", soilSolidity: ""},
        {points: 1, samplingDepth: "10~20", type: 2, wetWeight: "", dryWeight: "", soilMoisture: "", soilSolidity: ""},
        {points: 2, samplingDepth: "0~10", type: 1, wetWeight: "", dryWeight: "", soilMoisture: "", soilSolidity: ""},
        {points: 2, samplingDepth: "10~20", type: 2, wetWeight: "", dryWeight: "", soilMoisture: "", soilSolidity: ""},
        {points: 3, samplingDepth: "0~10", type: 1, wetWeight: "", dryWeight: "", soilMoisture: "", soilSolidity: ""},
        {points: 3, samplingDepth: "10~20", type: 2, wetWeight: "", dryWeight: "", soilMoisture: "", soilSolidity: ""},
      ],
      dataRule: {
        projectCode: [
          {required: true, message: '项目编号不能为空', trigger: 'blur'}
        ],

      }
    }
  },
  mounted() {
    this.getprojectList()
  },
  methods: {
    // 计算并更新平均湿度和固度
    calculateSoilMoisture(row) {
    // 如果湿重和干重都存在，计算土壤含水率
      if (row.wetWeight && row.dryWeight) {
        const wetWeight = parseFloat(row.wetWeight);
        const dryWeight = parseFloat(row.dryWeight);

        if (!isNaN(wetWeight) && !isNaN(dryWeight) && dryWeight !== 0) {
          // 计算土壤含水率百分比
          row.soilMoisture = ((wetWeight - dryWeight) / wetWeight * 100).toFixed(2);
        } else {
          row.soilMoisture = '';  // 如果输入无效，清空土壤含水率
        }
      } else {
        row.soilMoisture = '';  // 如果湿重或干重未输入，清空土壤含水率
      }

      this.calculateAverages(this.tableData)
    },
    // 计算0~10层和10~20层的平均值
    calculateAverages(tableData) {
      let totalSoilMoisture_0_10 = 0;
      let totalSoilSolidity_0_10 = 0;
      let totalSoilMoisture_10_20 = 0;
      let totalSoilSolidity_10_20 = 0;

      let count_0_10 = 0;
      let count_10_20 = 0;

      // 遍历 tableData 计算 0~10 和 10~20 层的平均值
      tableData.forEach(row => {
        // 计算0~10层平均值
        if (row.samplingDepth === "0~10") {
          if (row.soilMoisture !== "" && row.soilMoisture !== undefined) {
            totalSoilMoisture_0_10 += parseFloat(row.soilMoisture);
          }
          if (row.soilSolidity !== "" && row.soilSolidity !== undefined) {
            totalSoilSolidity_0_10 += parseFloat(row.soilSolidity);
          }
          count_0_10++;
        }

        // 计算10~20层平均值
        if (row.samplingDepth === "10~20") {
          if (row.soilMoisture !== "" && row.soilMoisture !== undefined) {
            totalSoilMoisture_10_20 += parseFloat(row.soilMoisture);
          }
          if (row.soilSolidity !== "" && row.soilSolidity !== undefined) {
            totalSoilSolidity_10_20 += parseFloat(row.soilSolidity);
          }
          count_10_20++;
        }
      });

      // 计算0~10层的平均值
      this.dataForm.waterLayerAverages10 = (count_0_10 > 0 ? totalSoilMoisture_0_10 / count_0_10 : 0).toFixed(2);
      this.dataForm.soilLayerAverages10 = (count_0_10 > 0 ? totalSoilSolidity_0_10 / count_0_10 : 0).toFixed(2);

      // 计算10~20层的平均值
      this.dataForm.waterLayerAverages20 = (count_10_20 > 0 ? totalSoilMoisture_10_20 / count_10_20 : 0).toFixed(2);
      this.dataForm.soilLayerAverages20 = (count_10_20 > 0 ? totalSoilSolidity_10_20 / count_10_20 : 0).toFixed(2);

      // 计算最终土壤含水率总平均值和总土壤坚实度
      const wavg = ((this.dataForm.waterLayerAverages10 || 0 + this.dataForm.waterLayerAverages20 || 0) / 2).toFixed(2);
      const savg = ((this.dataForm.soilLayerAverages10 || 0 + this.dataForm.soilLayerAverages20 || 0) / 2).toFixed(2);
      this.dataForm.waterAvg = wavg;
      this.dataForm.computeWaterAvg = wavg;
      this.dataForm.soilAvg = savg;
      this.dataForm.computeSoilAvg = savg;
    },

    //获取项目列表
    getprojectList() {
      this.$http({
        url: this.$http.adornUrl(`/reportapproval/product/getProjectNumber`),
        method: 'post',
        data: this.$http.adornData({})
      }).then((data) => {
        if (data && data.code === 0) {
          this.projectList = data.productList
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    init(id) {
      this.dataForm.id = id || 0
      this.selectDis = false
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/reportapproval/soilfirmnessmoisture/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then((data) => {
            if (data && data.code === 0) {
              this.dataForm.projectCode = data.soilFirmnessMoisture.projectCode
              this.dataForm.waterLayerAverages10 = data.soilFirmnessMoisture.waterLayerAverages10
              this.dataForm.waterLayerAverages20 = data.soilFirmnessMoisture.waterLayerAverages20
              this.dataForm.soilLayerAverages10 = data.soilFirmnessMoisture.soilLayerAverages10
              this.dataForm.soilLayerAverages20 = data.soilFirmnessMoisture.soilLayerAverages20
              this.dataForm.waterAvg = data.soilFirmnessMoisture.waterAvg
              this.dataForm.soilAvg = data.soilFirmnessMoisture.soilAvg
              this.dataForm.detectPeople = data.soilFirmnessMoisture.detectPeople
              this.dataForm.recorders = data.soilFirmnessMoisture.recorders
              this.dataForm.checkers = data.soilFirmnessMoisture.checkers
              this.dataForm.pdfPath = data.soilFirmnessMoisture.pdfPath
              this.dataForm.wordPath = data.soilFirmnessMoisture.wordPath
              this.dataForm.status = data.soilFirmnessMoisture.status
              this.tableData = data.soilFirmnessMoisture.soliChilds
              this.selectDis = true
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/reportapproval/soilfirmnessmoisture/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'projectCode': this.dataForm.projectCode,
              'waterLayerAverages10': this.dataForm.waterLayerAverages10,
              'waterLayerAverages20': this.dataForm.waterLayerAverages20,
              'soilLayerAverages10': this.dataForm.soilLayerAverages10,
              'soilLayerAverages20': this.dataForm.soilLayerAverages20,
              'waterAvg': this.dataForm.waterAvg,
              'soilAvg': this.dataForm.soilAvg,
              'detectPeople': this.dataForm.detectPeople,
              'recorders': this.dataForm.recorders,
              'checkers': this.dataForm.checkers,
              'pdfPath': this.dataForm.pdfPath,
              'wordPath': this.dataForm.wordPath,
              'soliChilds': this.tableData,
              'status': this.dataForm.status
            })
          }).then((data) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.warning(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
